<template>
  <div>
    <h3 class="title">{{ $t("task.title") }}</h3>
    <div class="search">
      <el-input
        class="input-with-select"
        :placeholder="$t('task.search.placeholder')"
        v-model="queryInfo.query_text"
      >
        <el-select
          v-model="queryInfo.query_type"
          slot="prepend"
          style="width: 140px"
        >
          <el-option
            v-for="item in $t('task.options')"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="primary" @click="searchTask">{{
        $t("task.search.searchBtn")
      }}</el-button>
      <el-button type="info" plain @click="resetSearch">{{
        $t("task.search.resetBtn")
      }}</el-button>
      <!-- <el-button
        type="success"
        plain
        icon="el-icon-circle-plus-outline"
        style="width: 220px"
        @click="createTask"
        >新建任务</el-button
      > -->
      <el-button
        type="success"
        plain
        icon="el-icon-circle-plus-outline"
        style="width: 280px"
        @click="createBatchTask"
        >{{ $t("task.search.projectCreated") }}</el-button
      >
    </div>
    <el-tabs v-model="queryInfo.task_type" @tab-click="handleClick">
      <el-tab-pane label="scrapyd" name="1"></el-tab-pane>
      <el-tab-pane label="python" name="2"></el-tab-pane>
    </el-tabs>
    <el-table
      v-loading="loading"
      element-loading-text="Loading...."
      :data="taskList"
      border
      width="100%"
      style="margin-top: -14px; min-height: 600px"
      ref="taskListRef"
      :key="queryInfo.task_type"
      @selection-change="getSelectedTask"
    >
      <!-- 任务下 关联爬虫 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div
            class="aboutReptileList"
            v-if="scope.row.reptileChildren.length != 0"
          >
            <h3 class="aboutReptileTitle">
              {{ $t("task.table.expand.title") }}
            </h3>
            <div class="aboutReptileContent">
              <el-table
                :data="scope.row.reptileChildren"
                border
                width="100%"
                ref="reptileListRef"
                :key="queryInfo.task_type"
                @selection-change="getSelectedReptile"
              >
                <el-table-column
                  type="index"
                  width="61"
                  :label="$t('task.table.expand.index')"
                ></el-table-column>
                <el-table-column
                  type="selection"
                  width="55"
                  v-if="queryInfo.task_type != 2"
                  key="3"
                >
                </el-table-column>
                <el-table-column
                  prop="en_name"
                  :label="$t('task.table.expand.name')"
                  sortable
                >
                </el-table-column>
                <el-table-column
                  prop="description"
                  :label="$t('task.table.expand.descript')"
                >
                </el-table-column>
                <!-- <el-table-column
                  prop="state"
                  :label="$t('task.table.expand.state')"
                  width="80"
                  sortable
                >
                  <template slot-scope="scope">
                    <el-button
                      v-if="scope.row.state"
                      type="text"
                      style="color: #f56c6c"
                      >{{ $t("task.table.expand.stateBtn.stop") }}</el-button
                    >
                    <el-button
                      v-if="!scope.row.state"
                      type="text"
                      @click="startReptile(scope)"
                      >{{ $t("task.table.expand.stateBtn.start") }}</el-button
                    >
                  </template>
                </el-table-column> -->
                <el-table-column
                  prop="status"
                  :label="$t('task.table.expand.warning')"
                  sortable
                >
                  <template slot-scope="{ row }">
                    <el-button
                      v-show="row.status == 1"
                      size="mini"
                      type="danger"
                      circle
                    ></el-button>
                    <el-button
                      v-show="row.status == 0"
                      size="mini"
                      type="success"
                      circle
                    ></el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="wrning_details"
                  :label="$t('task.table.expand.warningDetail')"
                >
                  <template slot-scope="{ row }">
                    <div v-if="row.status == 0">...</div>
                    <div
                      v-if="row.status == 1"
                      style="cursor: pointer"
                      @click="isWrningShow = !isWrningShow"
                      :class="isWrningShow ? 'wrning_details' : ''"
                    >
                      {{ row.wrning_details }}
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="primary"
                size="small"
                plain
                class="reptileStart"
                v-if="queryInfo.task_type != 2"
                @click="selectedReptileStart"
                >{{ $t("task.table.expand.reptileStart") }}</el-button
              >
            </div>
          </div>
          <div v-else style="width: 100%; padding-left: 20px">
            {{ $t("task.table.noReptile") }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        type="selection"
        width="55"
        v-if="queryInfo.task_type != 2"
        key="1"
      >
      </el-table-column>
      <el-table-column
        type="index"
        width="61"
        :label="$t('task.table.index')"
        :index="table_index"
      ></el-table-column>
      <el-table-column
        prop="name"
        :label="$t('task.table.name')"
        show-overflow-tooltip
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="project_name"
        :label="$t('task.table.project_name')"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="description"
        :label="$t('task.table.descript')"
        show-overflow-tooltip
      >
      </el-table-column>
      <!-- <el-table-column prop="state" label="状态" width="80" sortable>
        <template slot-scope="scope">
          <el-button
            v-show="scope.row.state"
            type="text"
            style="font-size: 20px; padding: 0; color: #67c23a"
            icon="el-icon-video-pause"
          ></el-button>
          <el-button
            v-show="!scope.row.state"
            style="font-size: 20px; padding: 0; color: #f56c6c; margin: 0"
            type="text"
            icon="el-icon-video-play"
          ></el-button>
        </template>
      </el-table-column> -->
      <el-table-column
        :label="$t('task.table.hostName')"
        sortable
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <span>{{ row.clients.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        :label="$t('task.table.hostIP')"
        sortable
      >
        <template slot-scope="{ row }">
          <span>{{ row.clients.ip }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="date"
        :label="$t('task.table.time')"
        sortable
        v-if="queryInfo.task_type != 2"
        key="2"
      >
        <template slot-scope="{ row }">
          <el-button type="text" @click="configTaskTime(row)">{{
            $t("task.btn.setup_time")
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('task.table.operation')" width="390">
        <template slot-scope="scope">
          <!-- <el-popconfirm
            :title="$t('task.btn.closeSure')"
            @confirm="closeTask(scope)"
            style="margin: 0 10px 0 0"
          > -->
          <el-button
            style="margin: 0 10px 0 0"
            :type="scope.row.status == 0 ? 'success' : 'info'"
            :icon="scope.row.id === currentId ? 'el-icon-loading' : ''"
            :disabled="scope.row.id === currentId ? true : false"
            size="mini"
            plain
            slot="reference"
            @click="handler(scope)"
            >{{ scope.row.status == 0 ? "start" : "pause" }}</el-button
          >
          <!-- </el-popconfirm> -->
          <el-popconfirm
            :title="$t('task.btn.copySure')"
            @confirm="copyTask(scope)"
            style="margin: 0 10px 0 0"
            :confirm-button-text="$t('task.btn.sure')"
            :cancel-button-text="$t('task.btn.cancel')"
          >
            <el-button
              type="primary"
              icon="el-icon-connection"
              size="mini"
              plain
              slot="reference"
              >{{ $t("task.btn.copy") }}</el-button
            >
          </el-popconfirm>

          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            plain
            @click="taskEditor(scope.row)"
            >{{ $t("task.btn.editor") }}</el-button
          >
          <el-popconfirm
            :title="$t('task.btn.delSure')"
            @confirm="delTask(scope)"
            style="margin: 0 0 0 10px"
            :confirm-button-text="$t('task.btn.sure')"
            :cancel-button-text="$t('task.btn.cancel')"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              plain
              slot="reference"
              >{{ $t("task.btn.delete") }}</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="footer">
      <!-- <el-button type="primary" size="mini" @click="reptileCurve"
          >关联爬虫统计曲线</el-button
        > -->
      <el-button
        type="primary"
        size="mini"
        @click="selectedTaskStart"
        v-if="queryInfo.task_type != 2"
        >{{ $t("task.btn.batch_task") }}</el-button
      >
      <el-pagination
        class="pagination"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <TaskCreatedDialog
      :taskCreatedDialogVisible="taskCreatedDialogVisible"
      @closeDialog="closeCreatedDialog"
    ></TaskCreatedDialog>
    <TaskEditorDialog
      :taskEditorDialogVisible="taskEditorDialogVisible"
      :taskEditorRow="taskEditorRow"
      :taskList="taskList"
      :projectList="projectList"
      :hostList="hostList"
      :reptileList="reptileList"
      @closeDialog="closeTaskEditorDialog"
    ></TaskEditorDialog>
    <TaskCreatedBatchDialog
      :taskCreatedBatchDialogVisible="taskCreatedBatchDialogVisible"
      :projectList="projectList"
      :hostList="hostList"
      :reptileList="reptileList"
      @closeDialog="closeCreatedBatchDialog"
    ></TaskCreatedBatchDialog>
    <TaskConfigTimeDialog
      :taskCreatedBatchInnerDialogVisible="taskCreatedBatchInnerDialogVisible"
      :taskRow="taskRow"
      @closeDialog="closeInnerDialog"
      @saveTime="saveTime"
    ></TaskConfigTimeDialog>
  </div>
</template>

<script>
import TaskCreatedDialog from "../../../components/TaskCreatedDialog.vue";
import TaskEditorDialog from "../../../components/TaskEditorDialog.vue";
import TaskCreatedBatchDialog from "../../../components/TaskCreatedBatchDialog.vue";
import TaskConfigTimeDialog from "../../../components/TaskConfigTimeDialog.vue";
export default {
  components: {
    TaskCreatedDialog,
    TaskEditorDialog,
    TaskCreatedBatchDialog,
    TaskConfigTimeDialog,
  },
  data() {
    return {
      currentId: 0,
      start_state: false,
      start_loading: false,
      loading: true,
      // 控制告警详情内容是否展开
      isWrningShow: false,
      // 分页参数
      queryInfo: {
        page: 1,
        pagesize: 10,
        query_text: "",
        query_type: 1,
        task_type: "1",
      },
      // 任务数据总数
      total: 0,
      // 控制配置时间对话框的显示与隐藏
      taskCreatedBatchInnerDialogVisible: false,
      // 是否是嵌套对话框
      isInner: false,
      // 任务列表
      taskList: [],
      // 搜索文字
      searchText: "",
      // 控制任务编辑对话框的显示与隐藏
      taskEditorDialogVisible: false,
      // 控制新建任务对话框的显示与隐藏
      taskCreatedDialogVisible: false,
      // 控制批量创建任务对话框的显示与隐藏
      taskCreatedBatchDialogVisible: false,
      // 任务ID
      taskEditorId: "",
      // 选中的字段
      select: "",
      options: this.$t("task.options"),
      // 项目列表
      projectList: [],
      // 主机列表
      hostList: [],
      // 爬虫列表
      reptileList: [],
      // 整行数据
      taskRow: "",
      // 选中的爬虫列表
      selectedReptileList: [],
      // 选中的任务列表
      selectedTaskList: [],
      // 编辑任务行数据
      taskEditorRow: "",
    };
  },
  created() {
    if (this.$route.query.en_name) {
      let index = this.$route.query.en_name.indexOf("/");
      this.queryInfo.query_text = this.$route.query.en_name.slice(index + 1);
    }
    this.getTaskList();
    this.getHostList();
  },
  methods: {
    async handler(scope) {
      // 0是处于启动状态  1是处于关闭状态
      let type = scope.row.status === 0 ? 1 : 0;
      this.currentId = scope.row.id;
      const { data: res } = await this.$http.get("/task/set_status", {
        params: { task_id: scope.row.id, type: type },
      });
      if (res.code != 0) {
        this.$message.error("操作失败！");
      } else {
        this.$message.success(res.msg);
        scope.row.status = type;
      }
      this.currentId = 0;

      // setTimeout(() => {
      //   this.currentId = 0;
      //   scope.row.status = 1;
      //   //   this.start_loading = false;
      //   //   this.start_state = !this.start_state;
      // }, 2000);
    },
    // tabs 选项卡切换触发函数
    handleClick(tab, event) {
      this.queryInfo.page = 1;
      this.getTaskList();
    },
    // 点击搜索按钮
    searchTask() {
      console.log(this.queryInfo);
      // console.log("搜索功能");
      this.getTaskList();
    },
    // 点击重置按钮
    resetSearch() {
      this.queryInfo.query_text = "";
      this.queryInfo.query_type = 1;
      this.getTaskList();
    },
    // 当前页数
    handleCurrentChange(val) {
      console.log("当前页数", val);
      this.queryInfo.page = val;
      this.getTaskList();
    },
    // 获取主机列表
    async getHostList() {
      const { data: res } = await this.$http.get("/host");
      this.hostList = res;
      console.log(this.hostList);
      console.log("------------主机列表数据-----------", res);
    },
    // 获取任务列表数据
    getTaskList() {
      this.loading = true;
      this.$http.get("/task/list", { params: this.queryInfo }).then((res) => {
        console.log("先看看获取到的数据？？", res.data);
        this.total = res.data.total;
        this.projectList = res.data.projects;
        this.reptileList = res.data.reptile_all;
        res.data.task // 将任务关联爬虫 添加到任务数据的reptileChildren属性中去
          .forEach((val) => {
            if (this.$utils.isJSON(val.spider)) {
              val.spider = JSON.parse(val.spider);
            } else {
              val.spider = [];
            }
            val.reptileChildren = res.data.reptiles.filter((vals) => {
              return val.spider.indexOf(vals.id) != -1;
            });
            val.project_name = res.data.projects.find((vals) => {
              return val.project_id == vals.id;
            }).name;
          });
        this.taskList = res.data.task;
        console.log("-----先看看任务列表数据-----", this.taskList);
        this.loading = false;
      });
    },
    // 获取选中的爬虫列表
    getSelectedReptile(val) {
      this.selectedReptileList = val;
    },
    // 批量开启爬虫
    async selectedReptileStart() {
      if (this.selectedReptileList.length == 0)
        return this.$message.info(this.$t("task.message.selectReptile"));
      console.log(this.selectedReptileList);

      let obj = {};
      let pro = this.projectList.find((val) => {
        return val.id == this.selectedReptileList[0].project_id;
      });
      obj.project_name = pro.name;
      obj.client_id = pro.client_id;
      obj.spider = [];
      this.selectedReptileList.forEach((val) => {
        obj.spider.push({ spider_name: val.en_name });
      });
      console.log(obj);
      const { data: res } = await this.$http.post("/crawler/Batch/start", [
        obj,
      ]);
      if (res.code == 0) {
        this.$message.success(this.$t("task.message.startRepSuccess"));
      } else {
        this.$message.error(this.$t("task.message.startRepError"));
      }
    },
    // 单个开启爬虫
    async startReptile(scope) {
      console.log(scope.row);
      let obj = {};
      let pro = this.projectList.find((val) => {
        return val.id == scope.row.project_id;
      });
      obj.project_name = pro.name;
      obj.client_id = pro.client_id;
      obj.spider_name = scope.row.en_name;
      const { data: res } = await this.$http.post("/project/start", obj);
      if (res.code == 0) {
        this.$message.success(this.$t("task.message.startRepSuccess"));
      } else {
        this.$message.error(this.$t("task.message.startRepError"));
      }
    },
    // 获取选中的任务列表
    getSelectedTask(val) {
      this.selectedTaskList = val;
    },
    // 批量开启任务
    async selectedTaskStart() {
      if (this.selectedTaskList.length == 0)
        return this.$message.info(this.$t("task.message.selectTask"));
      this.selectedTaskList.forEach((vals) => {
        vals.client_id = this.projectList.find((val) => {
          return val.id == vals.project_id;
        }).client_id;
      });
      let branchTask = [];
      this.selectedTaskList.forEach((val) => {
        let obj = {};
        obj.id = val.id;
        obj.project_name = val.project_name;
        obj.client_id = val.client_id;
        obj.spider = [];
        val.reptileChildren.forEach((vals) => {
          let obj1 = {};
          obj1.spider_name = vals.en_name;
          obj.spider.push(obj1);
        });
        branchTask.push(obj);
      });
      console.log(branchTask);
      const { data: res } = await this.$http.post(
        "/crawler/Batch/start",
        branchTask
      );
      if (res.code == 0) {
        this.$message.success(this.$t("task.message.startTaskSuccess"));
      } else {
        this.$message.error(this.$t("task.message.startTaskError"));
      }
    },

    // 关闭任务编辑对话框
    closeTaskEditorDialog(way) {
      this.taskEditorDialogVisible = false;
      if (way) return;
      this.getTaskList();
    },
    // 创建任务
    createTask() {
      this.taskCreatedDialogVisible = true;
      console.log("创建任务");
    },
    // 关闭创建任务对话框
    closeCreatedDialog() {
      this.taskCreatedDialogVisible = false;
    },
    // 批量创建任务
    createBatchTask() {
      this.taskCreatedBatchDialogVisible = true;
      console.log("批量创建任务");
    },
    // 关闭批量创建对话框
    closeCreatedBatchDialog(way) {
      this.taskCreatedBatchDialogVisible = false;
      if (way) return;
      this.getTaskList();
    },
    // 配置时间对话框
    configTaskTime(row) {
      // console.log(row.configuration);
      this.taskRow = row;
      this.taskCreatedBatchInnerDialogVisible = true;
    },
    saveTime(val) {
      console.log(val);
    },
    // 关闭配置时间对话框
    closeInnerDialog(way) {
      this.taskCreatedBatchInnerDialogVisible = false;
      if (way) return;
      this.getTaskList();
    },
    // 编辑任务
    taskEditor(row) {
      console.log(row);
      this.taskEditorRow = row;
      // this.taskEditorId = id;
      this.taskEditorDialogVisible = true;
    },
    // 删除任务
    delTask(scope) {
      console.log(scope.row.id);
      this.$http
        .get("/task/del", { params: { id: scope.row.id } })
        .then((res) => {
          if (res.data.code != 0)
            return this.$message.error(this.$t("task.message.del_error"));
          this.$message.success(this.$t("task.message.del_success"));
          this.getTaskList();
        });
    },
    // 解决表格序号分页后不连续的问题
    table_index(index) {
      return (this.queryInfo.page - 1) * this.queryInfo.pagesize + index + 1;
    },
    // 关闭任务
    async closeTask(scope) {
      let client_id = this.projectList.find((val) => {
        return val.id == scope.row.project_id;
      }).client_id;
      const { data: res } = await this.$http.get("/task/cancel", {
        params: {
          client_id: client_id,
          project_name: scope.row.project_name,
          task_id: scope.row.id,
        },
      });
      console.log(res);
      if (res.code != 0)
        return this.$message.error(this.$t("task.message.close_err"));
      this.$message.success(this.$t("task.message.close_succ"));
    },
    // 复制任务
    copyTask(scope) {
      console.log(scope.row);
      this.$http
        .get("task/copy", { params: { id: scope.row.id } })
        .then((res) => {
          if (res.data.code == 0) {
            this.$message.success(this.$t("task.message.copy_success"));
          } else {
            this.$message.success(this.$t("task.message.copy_error"));
          }
        });
      this.getTaskList();
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  color: #606266;
}
.search {
  margin: 10px 0;
  .el-input {
    width: 34%;
  }
  .el-button {
    margin-left: 10px;
  }
}
// 下拉爬虫样式
.aboutReptileList {
  // display: flex;
  margin-left: 1%;
  .aboutReptileTitle {
    // width: 50%;
    // word-break: break-all;
    padding: 2px 0 2px 20px;
    // height: 120px;
    border-radius: 20px 20px 0px 0px;
    // text-align: center;
    background-color: #b7c2ff;
    color: #606266;
  }
  .aboutReptileContent {
    // width: 97%;
    border: 1px solid #b7c2ff;
    .reptileStart {
      margin: 10px;
    }
  }
}
.footer {
  display: flex;
  padding-top: 12px;
}
.wrning_details {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
</style>